package com.xiaogao.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.xiaogao.oss.service.OssService;
import com.xiaogao.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 小高
 * @createtime 2021-06-05-23:15
 * @description
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFile(MultipartFile file) {

        //获取阿里云存储相关常量
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        String uploadUrl = null;

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // 在文件名称里面添加随机唯一的值，replaceAll把名称中带“-”的去掉
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            // 把文件按照年月期进行分类
            // 获取当前日期
            String datePath = new DateTime().toString("yyyy/MM");
            // 拼接   例：2021/06/01/zsd762as5sda01.jpg
            fileName = datePath + "/" + fileName;

            // 调用OSS方法实现上传  参数：Bucket名称，文件路劲和文件名称(/images/1.jpg)，上传文件流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            inputStream.close();
            ossClient.shutdown();

            // 拼接阿里云oss文件路径
            //https://gxjy-xiaogao.oss-cn-shenzhen.aliyuncs.com/cae57fea880411ebb6edd017c2d2eca2.jpg
            uploadUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return uploadUrl;
    }

    // 删除封面
    @Override
    public void removeFile(String coverName) {
        //获取阿里云存储相关常量
        String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除指定版本的Object。
        ossClient.deleteObject(bucketName, coverName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
